import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../function/states/encyclopedia_state.dart';
import '../../function/states/user_state.dart';
import '../../function/routes/app_route_manager.dart';
import '../../function/widgets/animated_tap_widget.dart';

/// 收藏百科页面
class FavoriteEncyclopediaPage extends StatefulWidget {
  const FavoriteEncyclopediaPage({super.key});

  @override
  State<FavoriteEncyclopediaPage> createState() =>
      _FavoriteEncyclopediaPageState();
}

class _FavoriteEncyclopediaPageState extends State<FavoriteEncyclopediaPage> {
  int _currentTabIndex = 0;
  late PageController _pageController;

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: _currentTabIndex);

    // 监听百科数据变化
    EncyclopediaState.encyclopediaListBeacon.subscribe((encyclopediaList) {
      if (mounted) {
        setState(() {});
      }
    });

    // 监听用户收藏状态变化
    EncyclopediaState.userFavoritesMapBeacon.subscribe((favoritesMap) {
      if (mounted) {
        setState(() {});
      }
    });
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final currentUser = UserState.getCurrentUserInfo();
    if (currentUser == null) {
      return Scaffold(
        body: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/common_bg.png'),
              fit: BoxFit.cover,
            ),
          ),
          child: SafeArea(
            child: Center(
              child: Text('Please login first')
                  .fontSize(18.sp)
                  .textColor(Colors.white)
                  .textAlignment(TextAlign.center),
            ),
          ),
        ),
      );
    }

    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/common_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏
              _buildTopNavigationBar(),

              SizedBox(height: 20.h),

              // 标签页切换
              _buildTabSection(),

              SizedBox(height: 16.h),

              // 内容区域
              Expanded(
                child: PageView(
                  controller: _pageController,
                  onPageChanged: (index) {
                    setState(() {
                      _currentTabIndex = index;
                    });
                  },
                  children: [
                    _buildTabContent('plant'), // 植物百科
                    _buildTabContent('animal'), // 动物百科
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopNavigationBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 0.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => AppRouteManager.goBack(),
            child: Row(
              children: [
                Icon(Icons.chevron_left, color: Colors.white, size: 26.w),
                SizedBox(width: 12.w),

                Text('Favorite Encyclopedia')
                    .fontSize(18.sp)
                    .textColor(Colors.white)
                    .fontFamily(
                      GoogleFonts.quicksand(
                        fontWeight: FontWeight.w700,
                      ).fontFamily,
                    )
                    .fontWeight(FontWeight.w700)
                    .textAlignment(TextAlign.center),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建标签页切换区域
  Widget _buildTabSection() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 20.w),
      child: Row(
        children: [
          // 植物标签
          GestureDetector(
            onTap: () {
              setState(() => _currentTabIndex = 0);
              _pageController.animateToPage(
                0,
                duration: Duration(milliseconds: 300),
                curve: Curves.easeInOut,
              );
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 5.h),
              decoration: BoxDecoration(
                color:
                    _currentTabIndex == 0
                        ? const Color(0x33663508)
                        : Colors.transparent,
                borderRadius: BorderRadius.circular(16.r),
                border: Border.all(
                  color:
                      _currentTabIndex == 0 ? Colors.white : Colors.transparent,
                  width: 0.4.w,
                ),
              ),
              child: Text('Plant')
                  .fontSize(12.sp)
                  .textColor(
                    _currentTabIndex == 0
                        ? Colors.white
                        : Colors.white.withOpacity(0.7),
                  )
                  .fontFamily(
                    GoogleFonts.quicksand(
                      fontWeight: FontWeight.w500,
                    ).fontFamily,
                  )
                  .fontWeight(FontWeight.w500)
                  .textAlignment(TextAlign.center),
            ),
          ),
          SizedBox(width: 20.w),
          // 动物标签
          GestureDetector(
            onTap: () {
              setState(() => _currentTabIndex = 1);
              _pageController.animateToPage(
                1,
                duration: Duration(milliseconds: 300),
                curve: Curves.easeInOut,
              );
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 5.h),
              decoration: BoxDecoration(
                color:
                    _currentTabIndex == 1
                        ? const Color(0x33663508)
                        : Colors.transparent,
                borderRadius: BorderRadius.circular(16.r),
                border: Border.all(
                  color:
                      _currentTabIndex == 1 ? Colors.white : Colors.transparent,
                  width: 0.4.w,
                ),
              ),
              child: Text('Animal')
                  .fontSize(12.sp)
                  .textColor(
                    _currentTabIndex == 1
                        ? Colors.white
                        : Colors.white.withOpacity(0.7),
                  )
                  .fontFamily(
                    GoogleFonts.quicksand(
                      fontWeight: FontWeight.w500,
                    ).fontFamily,
                  )
                  .fontWeight(FontWeight.w500)
                  .textAlignment(TextAlign.center),
            ),
          ),
          // 占位空间，让Tab靠左
          Spacer(),
        ],
      ),
    );
  }

  /// 构建标签页内容
  Widget _buildTabContent(String category) {
    final currentUser = UserState.getCurrentUserInfo();
    if (currentUser == null) return Container();

    final favoriteList =
        EncyclopediaState.getUserFavoriteEncyclopedia(
          currentUser.userId,
        ).where((item) => item.category == category).toList();

    if (favoriteList.isEmpty) {
      return _buildEmptyState(category);
    }

    return SingleChildScrollView(
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 20.w),
        child: _buildStaggeredGrid(favoriteList),
      ),
    );
  }

  /// 构建空状态
  Widget _buildEmptyState(String category) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset('assets/images/empty.png', width: 120.w, height: 120.w),
          SizedBox(height: 20.h),
          Text('No ${category == 'plant' ? 'plant' : 'animal'} favorites yet')
              .fontSize(16.sp)
              .textColor(Colors.white.withOpacity(0.6))
              .fontWeight(FontWeight.w400)
              .fontFamily(
                GoogleFonts.quicksand(fontWeight: FontWeight.w400).fontFamily,
              ),
        ],
      ),
    );
  }

  /// 构建交错网格布局
  Widget _buildStaggeredGrid(List<dynamic> encyclopediaList) {
    // 将列表分为两列，创建不同高度的卡片
    final leftColumnItems = <Widget>[];
    final rightColumnItems = <Widget>[];

    for (int i = 0; i < encyclopediaList.length; i++) {
      final encyclopedia = encyclopediaList[i];

      if (i % 2 == 0) {
        rightColumnItems.add(_buildEncyclopediaCard(encyclopedia, false));
        rightColumnItems.add(SizedBox(height: 16.h));
      } else {
        leftColumnItems.add(_buildEncyclopediaCard(encyclopedia, true));
        leftColumnItems.add(SizedBox(height: 16.h));
      }
    }

    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 左列 - 占剩余可用宽度的 192/343
        Flexible(flex: 192, child: Column(children: leftColumnItems)),

        SizedBox(width: 12.w),

        // 右列 - 占剩余可用宽度的 141/343
        Flexible(flex: 141, child: Column(children: rightColumnItems)),
      ],
    );
  }

  /// 构建单个百科卡片
  Widget _buildEncyclopediaCard(dynamic encyclopedia, bool isLeftColumn) {
    // 根据列位置设置不同的宽高比
    final screenHeight = MediaQuery.of(context).size.height;

    // 左列卡片：宽高比 192/218
    // 右列卡片：宽高比 141/165
    final cardHeight =
        isLeftColumn
            ? screenHeight *
                (218 / 812) // 左列高度比例
            : screenHeight * (165 / 812); // 右列高度比例

    // 根据宽高比计算卡片宽度
    final cardWidth =
        isLeftColumn
            ? screenHeight *
                (218 / 812) *
                (192 / 218) // 左列：高度 * (192/218)
            : screenHeight * (165 / 812) * (141 / 165); // 右列：高度 * (141/165)

    return AnimatedTapWidget(
      onTap: () {
        // 跳转到百科详情页
        AppRouteManager.navigateToEncyclopediaDetail(
          encyclopedia.encyclopediaId,
        );
      },
      child: Container(
        width: cardWidth,
        height: cardHeight,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12.r),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 8.r,
              offset: Offset(0, 4.h),
            ),
          ],
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(16.r),
          child: Stack(
            children: [
              // 背景图片
              Positioned.fill(
                child: Image.asset(encyclopedia.imageUrl, fit: BoxFit.cover),
              ),

              // 渐变遮罩
              Positioned.fill(
                child: Container(
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [
                        Colors.transparent,
                        Colors.black.withOpacity(0.3),
                        Colors.black.withOpacity(0.7),
                      ],
                      stops: const [0.0, 0.6, 1.0],
                    ),
                  ),
                ),
              ),

              // 标题 - 左上角
              Positioned(
                top: 12.h,
                left: 12.w,
                right: 12.w,
                child: Text(encyclopedia.name)
                    .fontSize(16.sp)
                    .textColor(Colors.white)
                    .fontFamily(
                      GoogleFonts.quicksand(
                        fontWeight: FontWeight.w700,
                      ).fontFamily,
                    )
                    .fontWeight(FontWeight.w700)
                    .textAlignment(TextAlign.left),
              ),

              // View按钮 - 右下角
              Positioned(
                bottom: 12.h,
                right: 12.w,
                child: Container(
                  width: 37.w,
                  height: 37.w,
                  decoration: BoxDecoration(
                    color: const Color(0xFF663507).withOpacity(0.4),
                    borderRadius: BorderRadius.circular(25.r),
                    border: Border.all(
                      color: Colors.white.withAlpha(80),
                      width: 1.w,
                    ),
                  ),
                  child: Center(
                    child: Text('View')
                        .fontSize(11.sp)
                        .textColor(Colors.white)
                        .fontFamily(
                          GoogleFonts.quicksand(
                            fontWeight: FontWeight.w600,
                          ).fontFamily,
                        )
                        .fontWeight(FontWeight.w600),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
